﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using AutoBuyWinform.entity;
using System.Collections;
using System.IO;

namespace AutoBuyWinform
{
    public partial class Form1 : Form
    {
        public static string webUrl;
        public static string chatUrl;
        public static string yjSendMsgUrl;
        public static string yjUpdateMsgUrl;
        public static string loginUrl;
        public static string logoutUrl;
        public static string captchaUrl;
        public static string postToCartUrl;
        public static string createOrderUrl;
        public static string yjPageUrl;
        public static string cartUrl;
        public static string searchUrl;
        public static int yj1;
        public static int yj2;
        public static int yj3;
        public static int buyWaitTime;
        public static int timeLength;
        public static int searchWaitTime;
        public static int startBuy_h;
        public static int startBuy_m;
        public static int startbuy_s;
        private string loginName;
        private string pwd;

        private bool isLogin = false;
        //private Logs logs;
        public Operations operations;
        public static CookieContainer cc = new CookieContainer();
        private CookieCollection ccReturned;

        public ProductConditions productConditions;
        LogForm searchLogForm;

        private Thread t;

        //public List<Fq> fqList;
        //public class Fq{
        //    public Fq(String fqmc, String fqdm)
        //    {
        //        this.fqmc = fqmc;
        //        this.fqdm = fqdm;
        //    }
        //    private String fqmc{get;set;}
        //    private String fqdm{get;set;}
        //};

        public Form1()
        {
            InitializeComponent();

            initUrl();
            isLogin = false;
            //logs = new Logs(false);
            operations = new Operations();
            productConditions = new ProductConditions();

            //fqList = new List<Fq>();
            //fqList.Add(new Fq("特价商品", "210"));
            //fqList.Add(new Fq("疯狂抢购", "220"));
            //fqList.Add(new Fq("交易A区", "40"));
            //fqList.Add(new Fq("优品区", "60"));
            //fqList.Add(new Fq("梅钢专区", "90"));
            //fqList.Add(new Fq("宁钢专区", "80"));
            //fqList.Add(new Fq("生僻特价区", "70"));

            //URLsGrid.Rows.Add("http://fdc.baostar.com/package/T02217/4194691/");
            //URLsGrid.Rows.Add("http://fdc.baostar.com/package/T02217/412392/");
            //URLsGrid.Rows.Add("http://fdc.baostar.com/package/T02217/418521/");
            //URLsGrid.Rows.Add("http://fdc.baostar.com/package/T01758/71643");
            //URLsGrid.Rows.Add("http://fdc.baostar.com/package/T02217/410858/");
            //productConditionGrid.Rows.Add(new String[] { "普冷:TL10", "冷", "BLD", "2", "2", "1370", "1370", "0", "20", "5120" });
            //textLoginName.Text = "13958145485";
            //textPwd.Text = "syz10022316";
            
        }

        private void initUrl()
        {
            webUrl = textWebUrl.Text;
            if (webUrl == null || webUrl == "")
            {
                MessageBox.Show("请输入主页URL");
                return;
            }

            //webUrl = "http://beta.baostar.com";
            chatUrl = "http://chat.baostar.com";
            yjSendMsgUrl = chatUrl + "/message/new";
            yjUpdateMsgUrl = chatUrl + "/message/updates";
            loginUrl = webUrl;
            logoutUrl = "http://beta.baostar.com/account/logout/";
            captchaUrl = webUrl + "/captcha.gif?t=" + ((Int64)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString();
            postToCartUrl = webUrl + "/shopping/cart/packs/add/";
            createOrderUrl = webUrl + "/order/create_contract_without_bargaining/";
            cartUrl = webUrl + "/shopping/my-carts/";
            yjPageUrl = webUrl + "/shopping/group-number/new/";
            searchUrl = webUrl + "/T02217/search/";
        }

        

        private void btnLogin_Click(object sender, EventArgs e)
        {
            initUrl();

            loginName = textLoginName.Text;
            pwd = textPwd.Text;
            if (Util.isEmpty(loginName) || Util.isEmpty(pwd))
            {
                MessageBox.Show("请输入用户名密码");
            }

            //MessageBox.Show(((Int64)(DateTime.Now-new DateTime(1970,1,1)).TotalMilliseconds).ToString());

            string veriCode = operations.GetVeriCode(loginUrl,captchaUrl, Util.GetCookieContainerCopy(cc), out ccReturned);
            if (ccReturned != null)
                cc.Add(ccReturned);
            isLogin = operations.Login(loginUrl, loginName, pwd, veriCode, Util.GetCookieContainerCopy(cc), out ccReturned);
            if (ccReturned != null)
                cc.Add(ccReturned);

            //yj_hidden
            //YjPage yjPage = new YjPage();
            //foreach (Cookie cookieValue in cc.GetCookies(new Uri(Form1.webUrl)))
            //{
            //    yjPage.addCookie(cookieValue);
            //}
            //yjPage.resetUrl(Form1.cartUrl);
            //yjPage.resetTitle(Form1.cartUrl);
            //yjPage.Visible = true;
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            isLogin = operations.Logout(logoutUrl, Util.GetCookieContainerCopy(cc), out ccReturned);
            if (ccReturned != null)
                cc.Add(ccReturned);
            MessageBox.Show("已登出");
        }

        private bool initGlobalData()
        {
            if (!isLogin)
            {
                MessageBox.Show("请先登录");
                return false;
            }

            

            if (Int32.TryParse(textYj1.Text, out yj1))
            {
                yj1 = Int32.Parse(textYj1.Text);
            }
            else
            {
                MessageBox.Show("\"议价\"1.数字格式错误");
                return false;
            }

            if (Int32.TryParse(textYj1.Text, out yj2))
            {
                yj2 = Int32.Parse(textYj1.Text);
            }
            else
            {
                MessageBox.Show("\"议价\"2.数字格式错误");
                return false;
            }

            if (Int32.TryParse(textYj1.Text, out yj3))
            {
                yj3 = Int32.Parse(textYj1.Text);
            }
            else
            {
                MessageBox.Show("\"议价\"3.数字格式错误");
                return false;
            }



            if (Int32.TryParse(textBuyWaitTime.Text, out buyWaitTime))
            {
                buyWaitTime = Int32.Parse(textBuyWaitTime.Text);
            }
            else
            {
                MessageBox.Show("\"抢拍间隔\"数字格式错误");
                return false;
            }

            if (Int32.TryParse(textTimeLength.Text, out timeLength))
            {
                timeLength = Int32.Parse(textTimeLength.Text);
            }
            else
            {
                MessageBox.Show("\"抢拍时长\"数字格式错误");
                return false;
            }


            

            return true;
        }

        private bool initURLBuyData()
        {
            if (!initGlobalData())
                return false;

            if (URLsGrid.Rows.Count <= 1)
            {
                MessageBox.Show("请输入商品页面网址");
                return false;
            }

            if (Int32.TryParse(textStartBuy_h.Text, out startBuy_h))
            {
                startBuy_h = Int32.Parse(textStartBuy_h.Text);
            }
            else
            {
                MessageBox.Show("\"开始扫描时间\"数字格式错误");
                return false;
            }

            if (Int32.TryParse(textStartBuy_m.Text, out startBuy_m))
            {
                startBuy_m = Int32.Parse(textStartBuy_m.Text);
            }
            else
            {
                MessageBox.Show("\"开始扫描时间\"数字格式错误");
                return false;
            }

            if (Int32.TryParse(textStartBuy_s.Text, out startbuy_s))
            {
                startbuy_s = Int32.Parse(textStartBuy_s.Text);
            }
            else
            {
                MessageBox.Show("\"开始扫描时间\"数字格式错误");
                return false;
            }

            return true;
        }

        private bool initConditionData()
        {
            if (!initGlobalData())
                return false;


            if (productConditionGrid.Rows.Count <= 1)
            {
                MessageBox.Show("请输入商品条件");
                return false;
            }

            if (Int32.TryParse(textSearchWaitTime.Text, out searchWaitTime))
            {
                searchWaitTime = Int32.Parse(textSearchWaitTime.Text);
            }
            else
            {
                MessageBox.Show("\"扫描间隔\"数字格式错误");
                return false;
            }

            

            return true;

        }

        private void btnURLBuy_Click(object sender, EventArgs e)
        {
            if (!initURLBuyData())
                return;

            HashSet<String> urls = new HashSet<String>();
            for (int i = 0; i < URLsGrid.Rows.Count - 1; i++)
            {
                DataGridViewRow row = URLsGrid.Rows[i];
                urls.Add((String)row.Cells[0].Value);
            }

            LastTimeForm lastTimeForm = new LastTimeForm(urls,Util.GetCookieContainerCopy(cc));
            lastTimeForm.Visible = true;
            lastTimeForm.startLastTime();

            //string page = Util.GetPage(goodsUrl, Util.GetCookieContainerCopy(cc), out ccReturned);
            //cc.Add(ccReturned);
            //Product product = operations.GetProduct(page);

            //if (product == null)
            //{
            //    MessageBox.Show("没有找到商品信息");
            //    return;
            //}

            //operations.AddToCart(product, Util.GetCookieContainerCopy(cc));


            //DateTime startTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, startSearch_h, startSearch_m, startSearch_s);

            ////实例化Timer类，设置间隔时间为10000毫秒；   
            //long wt = (startTime.TimeOfDay.Ticks - DateTime.Now.TimeOfDay.Ticks) / 10000;
            //if (wt < 0) wt = 1;
            //System.Timers.Timer t = new System.Timers.Timer(wt);
            ////到达时间的时候执行事件；   
            //t.Elapsed += new System.Timers.ElapsedEventHandler(startURLBuy);
            ////设置是执行一次（false）还是一直执行(true)；   
            //t.AutoReset = false;
            ////是否执行System.Timers.Timer.Elapsed事件；  
            //t.Enabled = true;
            
        }

        private void bthConditionBuy_Click(object sender, EventArgs e)
        {
            initUrl();

            if (!initConditionData())
                return;

            if (!productConditions.readGrid(productConditionGrid))
                return;

            searchLogForm = new LogForm(productConditions, Util.GetCookieContainerCopy(cc));

            searchLogForm.Visible = true;
            searchLogForm.startSearch();
            
        }



        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void btnStopBuy_Click(object sender, EventArgs e)
        {
            Application.Exit();
            //foreach(Thread t in operations.getThreadContainer())
            //{
            //    if (t != null && t.IsAlive)
            //    {
            //        t.Abort();
            //    }
            //}
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            groupBox2.Width = this.Width - 30;


            groupBox1.Width = this.Width - 30;

            URLsGrid.Width = this.Width - 60;

            productConditionGrid.Width = this.Width - 60;
        }

        private WebForm wf;

        private void button1_Click(object sender, EventArgs e)
        {
            wf = new WebForm();
            string page = wf.getPage("http://fdc.baostar.com/search/?mymall=1&time=616378750&itemName=%E6%99%AE%E5%86%B7&sfCate=TL10&thick=0-10&width=1000-1370&sfWeight=0-20");
            MessageBox.Show(page);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Console.WriteLine(wf.getPageString());
        }

        private void button3_Click(object sender, EventArgs e)
        {
            wf.clickPageNo(2);
        }

        /// <summary>
        /// 保存条件信息到文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveConditionBtn_Click(object sender, EventArgs e)
        {
            if (productConditionGrid.Rows.Count <= 1)
            {
                MessageBox.Show("请输入商品条件");
                return;
            }

            using(StreamWriter sw = new StreamWriter("Conditions.txt"))
            {
                StringBuilder sb = new StringBuilder();
                for(int i=0;i<productConditionGrid.Rows.Count-1;i++)
                {
                    DataGridViewRow row = productConditionGrid.Rows[i];
                    sb.Remove(0, sb.Length);

                    for(int j=0;j<row.Cells.Count;j++)
                    {
                        sb.Append(row.Cells[j].Value).Append("\t");
                    }

                    sw.WriteLine(sb.ToString());

                }
            }

        }



        /// <summary>
        /// 从文件读取条件信息
        /// </summary>
        private void loadConditionBtn_Click(object sender, EventArgs e)
        {
            using (StreamReader sr = new StreamReader("Conditions.txt"))
            {

                while (!sr.EndOfStream)
                {
                    string s = sr.ReadLine();
                    string[] ss = s.Split('\t');

                    productConditionGrid.Rows.Add(ss);


                }
            }
        }

       
        

        

    }
}
